#！/bin/bash
# version: 1.2
# date: 2022/05/31
# 可选依赖包: bc
# 安装命令: sudo pacman -S bc

# 调用函数,必须先定义网卡$eth
function get_bytes {
    # 获取当前时刻网口接收与发送的流量
    RXpre=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $2}')
    TXpre=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $10}')

    # 获取几秒后网口接收与发送的流量
    sleep $sleeptime
    RXnext=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $2}')
    TXnext=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $10}')

    # 获取这几秒钟实际的进出流量
    RX=$((${RXnext}-${RXpre}))
    TX=$((${TXnext}-${TXpre}))

    # 定义的原因和 间隔秒数、每间隔多少秒有多少字节传输 相关
    numbermbb=`echo | awk "{print $sleeptime*1024*1024}"`
    
    # 判断接收流量如果大于MB数量级则显示MB单位,否则显示KB数量级
    if [[ $RX -gt $numbermbb ]];then
        # RESULT=`echo "scale=2; $RX/$numbermbb" | bc`
        RESULT=`echo $RX $numbermbb|awk '{printf ("%.2f\n", $1/$2)}'`
        RX=$(echo $RESULT MB/s)
    else
        # RESULT=`echo "scale=2; $RX/1024" | bc`
        RESULT=`echo $RX|awk '{printf ("%.2f\n", $1/1024)}'`
        RX=$(echo $RESULT KB/s)
    fi
    
    # 判断发送流量如果大于MB数量级则显示MB单位,否则显示KB数量级
    if [[ $TX -gt $numbermbb ]];then
        # RESULT=`echo "scale=2; $TX/$numbermbb" | bc`
        RESULT=`echo $TX $numbermbb|awk '{printf ("%.2f\n", $1/$2)}'`
        TX=$(echo $RESULT MB/s)
    else
        # RESULT=`echo "scale=2; $TX/1024" | bc`
        RESULT=`echo $TX|awk '{printf ("%.2f\n", $1/1024)}'`
        TX=$(echo $RESULT KB/s)
    fi

    # 打印实时流量
    printf " $RX |  $TX"
}

get_wifi_info(){
    get_zh_lang=`echo $LANG|grep 'zh_CN'|wc -l`
    get_en_lang=`echo $LANG|grep 'en_US'|wc -l`

    if [ $get_zh_lang -eq 1 ];then
        #echo "zh_CN"
        wifiStatus=`nmcli | grep "已连接" | awk '{print $NF}' | wc -l`
        wifiName=`nmcli | grep "已连接" | awk '{print $NF}'`
    fi

    if [ $get_en_lang -eq 1 ];then
        #echo "en_US"
        wifiStatus=`nmcli | grep 'connected' | grep wlan0 | head -1 | awk '{print $NF}' | wc -l`
        wifiName=`nmcli | grep 'connected' | grep wlan0 | head -1 | awk '{print $NF}'`
    fi
}

# 定义有线网卡名
networkEth=enp2s0f0
# 定义无线网卡名
networkWifi=wlan0
# 定义计算的睡眠时间(s)【可以设置 1s 0.5s】
sleeptime=1

get_wifi_info

if [ $wifiStatus -eq 0 ]; then
    echo
else
    eth=$networkWifi
    get_bytes && printf " | " && echo $wifiName
fi

